package com.nanhai.buddhist.college.module.collegebase.controller.admin.departments;

import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils;
import com.nanhai.buddhist.college.framework.excel.core.util.ExcelUtils;
import com.nanhai.buddhist.college.framework.operatelog.core.annotations.OperateLog;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.departments.vo.*;
import com.nanhai.buddhist.college.module.collegebase.convert.departments.DepartmentsConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.colleges.CollegesDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.departments.DepartmentsDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.professions.ProfessionsDO;
import com.nanhai.buddhist.college.module.collegebase.service.departments.DepartmentsService;
import com.nanhai.buddhist.college.module.collegebase.service.professions.ProfessionsService;
import com.nanhai.buddhist.college.module.system.api.user.AdminUserApi;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.error;
import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.success;
import static com.nanhai.buddhist.college.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.nanhai.buddhist.college.module.collegebase.enums.ErrorCodeConstants.CLASSES_NOT_DELETE_XIBY;

@Api(tags = "管理后台 - 学校管理--系部")
@RestController
@RequestMapping("/collegebase/departments")
@Validated
public class DepartmentsController {

    @Resource
    private DepartmentsService departmentsService;
    @Resource
    private ProfessionsService professionsService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @ApiOperation("创建学校管理--系部")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<String> createDepartments(@Valid @RequestBody DepartmentsCreateReqVO createReqVO) {
        return success(departmentsService.createDepartments(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新学校管理--系部")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> updateDepartments(@Valid @RequestBody DepartmentsUpdateReqVO updateReqVO) {
        departmentsService.updateDepartments(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除学校管理--系部")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> deleteDepartments(@RequestParam("id") String id) {

        List<ProfessionsDO> listDo = professionsService.getProfessionsListByDepartmentsId(id);
        if (listDo != null && listDo.size() > 0) {
            return error(CLASSES_NOT_DELETE_XIBY);
        }

        departmentsService.deleteDepartments(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得学校管理--系部")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<DepartmentsRespVO> getDepartments(@RequestParam("id") String id) {
        DepartmentsDO departments = departmentsService.getDepartments(id);
        return success(DepartmentsConvert.INSTANCE.convert(departments));
    }

    @GetMapping("/list")
    @ApiOperation("获得学校管理--系部列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<DepartmentsRespVO>> getDepartmentsList(@RequestParam("ids") Collection<String> ids) {
        List<DepartmentsDO> list = departmentsService.getDepartmentsList(ids);
        return success(DepartmentsConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得学校管理--系部分页")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<PageResult<DepartmentsRespVO>> getDepartmentsPage(@Valid DepartmentsPageReqVO pageVO) {
        PageResult<DepartmentsDO> pageResult = departmentsService.getDepartmentsPage(pageVO);


//        Set<String> strings = CollectionUtils.convertSet(pageResult.getList(), DepartmentsDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//            pageResult.getList().forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }


        return success(DepartmentsConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出学校管理--系部 Excel")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    @OperateLog(type = EXPORT)
    public void exportDepartmentsExcel(@Valid DepartmentsExportReqVO exportReqVO,
                                       HttpServletResponse response) throws IOException {
        List<DepartmentsDO> list = departmentsService.getDepartmentsList(exportReqVO);

//        Set<String> strings = CollectionUtils.convertSet(list, DepartmentsDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//            list.forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }
        // 导出 Excel
        List<DepartmentsExcelVO> datas = DepartmentsConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "学校管理--系部.xls", "数据", DepartmentsExcelVO.class, datas);
    }

    @GetMapping("/byCollege/list")
    @ApiOperation("获取系部列表")
    @ApiImplicitParam(name = "collegeId", value = "学院id", required = true, example = "1024,2048", dataTypeClass = String.class)
    public CommonResult<List<DepartmentsRespVO>> getDepartmentsListByCollegeId(@RequestParam("collegeId") String collegeId) {
        List<DepartmentsDO> list = departmentsService.getDepartmentsListByCollegeId(collegeId);
        return success(DepartmentsConvert.INSTANCE.convertList(list));
    }


    @GetMapping("/byClassesId/info")
    @ApiOperation("获得学校管理--系部")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<DepartmentsRespVO> getDepartmentDTOByClassesId(@RequestParam("id") String id) {
        DepartmentsDO departments = departmentsService.getDepartmentDTOByClassesId(id);
        return success(DepartmentsConvert.INSTANCE.convert(departments));
    }
}
